/* =================================
   计算组件交互逻辑
   ================================= */

document.addEventListener('DOMContentLoaded', function() {
    
    // 初始化计算组件
    initCalculationComponent();
    
    function initCalculationComponent() {
        // 绑定模式切换
        bindModeSwitch();
        
        // 绑定计算按钮
        bindCalculationButtons();
        
        // 绑定参数验证
        bindParameterValidation();
        
        // 绑定重置按钮
        bindResetButtons();
        
        // 初始化演示计算
        initDemoCalculation();
    }
    
    // =================================
    // 模式切换功能
    // =================================
    function bindModeSwitch() {
        const modeTabs = document.querySelectorAll('.mode-tab');
        const calcSections = document.querySelectorAll('.calc-section');
        
        modeTabs.forEach(tab => {
            tab.addEventListener('click', function() {
                const mode = this.dataset.mode;
                
                // 切换标签状态
                modeTabs.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                
                // 切换内容区域
                calcSections.forEach(section => {
                    section.classList.remove('active');
                });
                
                const targetSection = document.getElementById(mode + '-mode');
                if (targetSection) {
                    targetSection.classList.add('active');
                }
                
                // 重置计算状态
                resetCalculationState(mode);
                
                console.log(`切换到${mode === 'arterial' ? '干线协调优化' : '单点优化'}模式`);
            });
        });
    }
    
    // =================================
    // 计算按钮功能
    // =================================
    function bindCalculationButtons() {
        const calcButtons = document.querySelectorAll('.calc-btn.primary');
        
        calcButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                const activeMode = document.querySelector('.calc-section.active').id;
                
                if (activeMode === 'arterial-mode') {
                    startArterialCalculation();
                } else {
                    startSingleCalculation();
                }
            });
        });
        
        // 预览按钮
        const previewButtons = document.querySelectorAll('.calc-btn.secondary');
        previewButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                showNotification('预览功能开发中，敬请期待！', 'info');
            });
        });
    }
    
    // =================================
    // 干线协调优化计算
    // =================================
    function startArterialCalculation() {
        console.log('开始干线协调优化计算...');
        
        // 验证参数
        if (!validateArterialParameters()) {
            showNotification('参数验证失败，请检查输入值', 'error');
            return;
        }
        
        // 更新计算状态
        updateCalculationStatus('processing', '计算进行中');
        
        // 模拟计算过程
        simulateArterialCalculation();
    }
    
    function validateArterialParameters() {
        const params = {
            intersectionCount: document.getElementById('intersection-count')?.value,
            cycleLength: document.getElementById('cycle-length')?.value,
            greenWaveSpeed: document.getElementById('green-wave-speed')?.value,
            bandwidthTarget: document.getElementById('bandwidth-target')?.value,
            peakVolume: document.getElementById('peak-volume')?.value,
            saturationRatio: document.getElementById('saturation-ratio')?.value
        };
        
        // 基本验证
        for (const [key, value] of Object.entries(params)) {
            if (!value || value <= 0) {
                console.error(`参数 ${key} 无效: ${value}`);
                return false;
            }
        }
        
        // 专业验证
        if (params.saturationRatio > 1.0) {
            console.error('饱和度不能超过1.0');
            return false;
        }
        
        if (params.bandwidthTarget > 90) {
            console.error('带宽目标不能超过90%');
            return false;
        }
        
        console.log('干线参数验证通过', params);
        return true;
    }
    
    function simulateArterialCalculation() {
        const steps = [
            { name: '参数验证', duration: 500 },
            { name: '流量建模', duration: 2000 },
            { name: '协调计算', duration: 3000 },
            { name: '方案优化', duration: 2500 },
            { name: '结果生成', duration: 1000 }
        ];
        
        let currentStep = 0;
        
        function executeStep() {
            if (currentStep >= steps.length) {
                // 计算完成
                completeArterialCalculation();
                return;
            }
            
            const step = steps[currentStep];
            updateStepStatus(currentStep, 'processing');
            addLogEntry('info', `开始${step.name}...`);
            
            setTimeout(() => {
                updateStepStatus(currentStep, 'completed');
                addLogEntry('success', `${step.name}完成`);
                currentStep++;
                setTimeout(executeStep, 200);
            }, step.duration);
        }
        
        executeStep();
    }
    
    function completeArterialCalculation() {
        updateCalculationStatus('completed', '计算完成');
        addLogEntry('success', '干线协调优化计算成功完成');
        
        // 更新结果指标
        updateArterialResults();
        
        showNotification('干线协调优化计算完成！', 'success');
    }
    
    function updateArterialResults() {
        // 模拟优化结果
        const results = {
            efficiency: 85.6 + Math.random() * 10,
            delay: 32.5 - Math.random() * 5,
            bandwidth: 67.8 + Math.random() * 15,
            fuel: 8.9 - Math.random() * 2
        };
        
        // 更新指标卡片
        updateMetricCard('协调效率', results.efficiency, '%');
        updateMetricCard('平均延误', results.delay, 's');
        updateMetricCard('绿波带宽', results.bandwidth, '%');
        updateMetricCard('燃油消耗', results.fuel, 'L/km');
        
        console.log('干线优化结果已更新', results);
    }
    
    // =================================
    // 单点优化计算
    // =================================
    function startSingleCalculation() {
        console.log('开始单点优化计算...');
        
        // 验证参数
        if (!validateSingleParameters()) {
            showNotification('参数验证失败，请检查输入值', 'error');
            return;
        }
        
        // 模拟快速计算
        simulateSingleCalculation();
    }
    
    function validateSingleParameters() {
        const intersectionName = document.getElementById('intersection-name')?.value;
        const phaseCount = document.getElementById('phase-count')?.value;
        const singleCycle = document.getElementById('single-cycle')?.value;
        
        if (!intersectionName?.trim()) {
            console.error('路口名称不能为空');
            return false;
        }
        
        if (!phaseCount || !singleCycle) {
            console.error('相位数量和周期时长必须设置');
            return false;
        }
        
        // 验证流量输入
        const flowInputs = document.querySelectorAll('#single-mode .flow-inputs input');
        let hasValidFlow = false;
        
        flowInputs.forEach(input => {
            if (input.value && input.value > 0) {
                hasValidFlow = true;
            }
        });
        
        if (!hasValidFlow) {
            console.error('至少需要输入一个有效的流量值');
            return false;
        }
        
        console.log('单点参数验证通过');
        return true;
    }
    
    function simulateSingleCalculation() {
        addLogEntry('info', '开始单点优化计算...');
        
        // 模拟较快的计算过程
        setTimeout(() => {
            addLogEntry('success', '参数验证完成');
            
            setTimeout(() => {
                addLogEntry('info', '正在计算最优配时...');
                
                setTimeout(() => {
                    addLogEntry('success', '配时方案生成完成');
                    completeSingleCalculation();
                }, 1500);
            }, 800);
        }, 300);
    }
    
    function completeSingleCalculation() {
        addLogEntry('success', '单点优化计算完成');
        
        // 更新单点结果
        updateSingleResults();
        
        showNotification('单点优化计算完成！', 'success');
    }
    
    function updateSingleResults() {
        const results = {
            delay: 28.5 - Math.random() * 5,
            saturation: 0.78 - Math.random() * 0.1,
            capacity: 3245 + Math.random() * 300
        };
        
        // 更新单点指标
        const singleMetrics = document.querySelector('.single-metrics');
        if (singleMetrics) {
            const cards = singleMetrics.querySelectorAll('.metric-card');
            
            if (cards[0]) {
                updateSingleMetricCard(cards[0], results.delay.toFixed(1), 's');
            }
            if (cards[1]) {
                updateSingleMetricCard(cards[1], results.saturation.toFixed(2), '');
            }
            if (cards[2]) {
                updateSingleMetricCard(cards[2], Math.round(results.capacity), '辆/h');
            }
        }
        
        console.log('单点优化结果已更新', results);
    }
    
    // =================================
    // 工具函数
    // =================================
    function updateCalculationStatus(status, text) {
        const statusText = document.querySelector('.status-text');
        const statusIndicator = document.querySelector('.status-indicator');
        
        if (statusText) statusText.textContent = text;
        if (statusIndicator) {
            statusIndicator.className = `status-indicator ${status}`;
        }
    }
    
    function updateStepStatus(stepIndex, status) {
        const steps = document.querySelectorAll('.step-item');
        if (steps[stepIndex]) {
            steps[stepIndex].className = `step-item ${status}`;
        }
    }
    
    function updateStepProgress(stepIndex, progress) {
        const steps = document.querySelectorAll('.step-item');
        if (steps[stepIndex]) {
            const progressFill = steps[stepIndex].querySelector('.progress-fill');
            const progressText = steps[stepIndex].querySelector('.progress-text');
            
            if (progressFill) {
                progressFill.style.width = `${Math.min(progress, 100)}%`;
            }
            if (progressText) {
                progressText.textContent = `${Math.round(Math.min(progress, 100))}%`;
            }
        }
    }
    
    function addLogEntry(level, message) {
        const logContent = document.querySelector('.log-content');
        if (!logContent) return;
        
        const timestamp = new Date().toLocaleTimeString();
        const logEntry = document.createElement('div');
        logEntry.className = `log-entry ${level}`;
        logEntry.innerHTML = `
            <span class="log-time">${timestamp}</span>
            <span class="log-level">[${level.toUpperCase()}]</span>
            <span class="log-message">${message}</span>
        `;
        
        logContent.appendChild(logEntry);
        logContent.scrollTop = logContent.scrollHeight;
    }
    
    function updateMetricCard(label, value, unit) {
        const metricCards = document.querySelectorAll('.metric-card');
        
        metricCards.forEach(card => {
            const cardLabel = card.querySelector('.metric-label');
            if (cardLabel && cardLabel.textContent === label) {
                const valueSpan = card.querySelector('.value');
                const unitSpan = card.querySelector('.unit');
                
                if (valueSpan) valueSpan.textContent = value.toFixed(1);
                if (unitSpan) unitSpan.textContent = unit;
            }
        });
    }
    
    function updateSingleMetricCard(card, value, unit) {
        const valueSpan = card.querySelector('.value');
        const unitSpan = card.querySelector('.unit');
        
        if (valueSpan) valueSpan.textContent = value;
        if (unitSpan) unitSpan.textContent = unit;
    }
    
    function resetCalculationState(mode) {
        // 重置计算状态
        updateCalculationStatus('ready', '准备就绪');
        
        // 重置步骤状态
        const steps = document.querySelectorAll('.step-item');
        steps.forEach((step, index) => {
            if (index === 0) {
                step.className = 'step-item completed';
            } else if (index === 1) {
                step.className = 'step-item processing';
            } else {
                step.className = 'step-item pending';
            }
        });
        
        // 清空日志
        const logContent = document.querySelector('.log-content');
        if (logContent) {
            logContent.innerHTML = `
                <div class="log-entry info">
                    <span class="log-time">${new Date().toLocaleTimeString()}</span>
                    <span class="log-level">[INFO]</span>
                    <span class="log-message">系统准备就绪，等待开始计算...</span>
                </div>
            `;
        }
    }
    
    function previewCalculationResults() {
        showNotification('预览功能开发中，敬请期待！', 'info');
    }
    
    // =================================
    // 参数验证
    // =================================
    function bindParameterValidation() {
        const inputs = document.querySelectorAll('input[type="number"]');
        
        inputs.forEach(input => {
            input.addEventListener('blur', function() {
                validateInput(this);
            });
            
            input.addEventListener('input', function() {
                clearValidationError(this);
            });
        });
    }
    
    function validateInput(input) {
        const value = parseFloat(input.value);
        const min = parseFloat(input.min);
        const max = parseFloat(input.max);
        
        let isValid = true;
        let errorMessage = '';
        
        if (isNaN(value)) {
            isValid = false;
            errorMessage = '请输入有效数字';
        } else if (min !== undefined && value < min) {
            isValid = false;
            errorMessage = `值不能小于 ${min}`;
        } else if (max !== undefined && value > max) {
            isValid = false;
            errorMessage = `值不能大于 ${max}`;
        }
        
        if (!isValid) {
            showInputError(input, errorMessage);
        } else {
            clearInputError(input);
        }
        
        return isValid;
    }
    
    function showInputError(input, message) {
        input.style.borderColor = '#f44336';
        input.style.boxShadow = '0 0 0 2px rgba(244, 67, 54, 0.2)';
        
        // 显示错误提示
        let errorTip = input.parentNode.querySelector('.error-tip');
        if (!errorTip) {
            errorTip = document.createElement('span');
            errorTip.className = 'error-tip';
            errorTip.style.cssText = 'color: #f44336; font-size: 12px; margin-top: 4px; display: block;';
            input.parentNode.appendChild(errorTip);
        }
        errorTip.textContent = message;
    }
    
    function clearInputError(input) {
        input.style.borderColor = '';
        input.style.boxShadow = '';
        
        const errorTip = input.parentNode.querySelector('.error-tip');
        if (errorTip) {
            errorTip.remove();
        }
    }
    
    function clearValidationError(input) {
        clearInputError(input);
    }
    
    // =================================
    // 重置功能
    // =================================
    function bindResetButtons() {
        const resetBtns = document.querySelectorAll('.reset-btn');
        
        resetBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                const panel = this.closest('.input-panel');
                const inputs = panel.querySelectorAll('input, select');
                
                inputs.forEach(input => {
                    if (input.type === 'radio') {
                        input.checked = input.hasAttribute('checked');
                    } else {
                        input.value = input.defaultValue || '';
                    }
                    clearInputError(input);
                });
                
                showNotification('参数已重置', 'info');
            });
        });
    }
    
    // =================================
    // 演示计算初始化
    // =================================
    function initDemoCalculation() {
        // 初始化演示日志
        setTimeout(() => {
            addLogEntry('info', '计算组件初始化完成');
            addLogEntry('success', '系统自检通过，所有模块正常');
            addLogEntry('info', '等待用户输入参数开始计算...');
        }, 1000);
        
        // 模拟实时数据更新
        setInterval(() => {
            updateDemoMetrics();
        }, 5000);
    }
    
    function updateDemoMetrics() {
        // 随机更新一些演示数据
        const metricCards = document.querySelectorAll('.metric-card');
        
        metricCards.forEach((card, index) => {
            if (Math.random() < 0.3) { // 30% 概率更新
                const valueSpan = card.querySelector('.value');
                if (valueSpan) {
                    const currentValue = parseFloat(valueSpan.textContent);
                    const variation = (Math.random() - 0.5) * 0.1; // ±5% 变化
                    const newValue = currentValue * (1 + variation);
                    valueSpan.textContent = newValue.toFixed(1);
                }
            }
        });
    }
    
    // =================================
    // 通知系统
    // =================================
    function showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            background: ${getNotificationColor(type)};
            color: white;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            z-index: 10000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            max-width: 300px;
            word-wrap: break-word;
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
    
    function getNotificationColor(type) {
        const colors = {
            success: '#4CAF50',
            error: '#f44336',
            warning: '#FF9800',
            info: '#2196F3'
        };
        return colors[type] || colors.info;
    }
    
    // =================================
    // 导出功能（示例）
    // =================================
    window.CalculationComponent = {
        startArterialCalculation,
        startSingleCalculation,
        validateArterialParameters,
        validateSingleParameters,
        updateCalculationStatus,
        addLogEntry,
        showNotification
    };
    
    console.log('计算组件初始化完成');
}); 